require 'dgo/table/table'
require 'dgo/geometry/rectangle'
require 'event_editor/event_dialog'
require 'event_editor/event_manager'

module EventEditor
  class EventControler
    include DGO::Geometry
    def initialize(model, event_list_panel)
      @model = model
      @event_list_panel = event_list_panel
      @event_list_panel.model = model
      @event_list_panel.controler = self
      @event_list_panel.grab_focus
      @event_manager = EventEditor::EventManager.new(model)

      @target = nil
      @signal_set = false
      self.init_menu
    end

    def set_signals(target)
      @event_list_panel.signal_connect('key-press-event') do |widget, event|
        case event.keyval
        when 100, 65535 # delete
          self.delete_event
        when 99  # copy
          self.copy_event
        when 118  # paste
          self.paste_event
        when 120 # cut
          self.cut_event
        end
      end
    end

    def init_menu
      @menu = Gtk::Menu.new
      
      @menu_item1 = Gtk::MenuItem.new("Start Position")
      @menu_item2 = Gtk::MenuItem.new("Create New event")
      @menu_item3 = Gtk::MenuItem.new("Delete")
      @menu_item4 = Gtk::MenuItem.new("Edit")
      @menu_item5 = Gtk::MenuItem.new("Copy")
      @menu_item6 = Gtk::MenuItem.new("Paste")
      
      @menu.append(@menu_item1)
      @menu.append(@menu_item2)
      @menu.append(@menu_item3)
      @menu.append(@menu_item4)
      @menu.append(@menu_item5)
      @menu.append(@menu_item6)
      
      @menu_item1.signal_connect('activate') do
        @event_manager.set_player_position(@model.map_model.map_id, @target.sx, @target.sy)
        self.refresh_screen
      end
      @menu_item2.signal_connect('activate') do
        self.add_new_event
      end
      @menu_item3.signal_connect('activate') do
        self.delete_event
      end
      @menu_item4.signal_connect('activate') do
        self.edit_event
      end
      @menu_item5.signal_connect('activate') do
        self.copy_event
      end
      @menu_item6.signal_connect('activate') do
        self.paste_event
      end
      @menu.show_all
    end

    def refresh_menu
      if @model.selected_event
        @menu_item1.sensitive = false # new pos
        @menu_item2.sensitive = false # create new event
        @menu_item3.sensitive = true # delete
        @menu_item4.sensitive = true # edit
      else
        @menu_item1.sensitive = true
        @menu_item2.sensitive = true
        @menu_item3.sensitive = false
        @menu_item4.sensitive = false
      end
    end

    def target=(target)
      @target = target
      self.set_signals(target)
    end
    
    def add_new_event
      @model.add_new_event(@target.sx, @target.sy)

      self.refresh_screen
      @event_list_panel.refresh
    end

    def cut_event
      self.copy_event
      self.delete_event
    end
    
    def copy_event
      $buffer['event'] = Marshal.dump(@model.selected_event)
    end
    
    def delete_event
      @model.delete_event(@model.selected_event)
      self.refresh_screen
      @event_list_panel.refresh
    end
    
    def paste_event
      return unless $buffer['event']
      @model.add_event(Marshal.load($buffer['event']), @target.sx, @target.sy)
      self.refresh_screen
      @event_list_panel.refresh
    end

    def edit_event
      EventDialog.show($window, @model) do |event|
        @model.events[@model.selected_event_no] = event
        @event_list_panel.refresh
      end
    end

    def on_double_clicked(event)
	  updateTargetCursorPosition(event)
      if @model.selected_event
        @target.left_pressed = false
        self.edit_event
      else
        self.add_new_event
      end
    end
    
	def updateTargetCursorPosition(event)
      @target.sx, @target.sy = @target.get_abs_location(event.x, event.y)
	  @target.ex, @target.ey = @target.sx, @target.sy
	end
	
    def on_left_down(event)
	  updateTargetCursorPosition(event)
      @model.select_event(@target.sx, @target.sy)
      
      @event_list_panel.select_row(@model.selected_event_no)
      
      self.refresh_screen
    end

    def on_left_up(event)
    
    end
    
    def on_right_down(event)
      updateTargetCursorPosition(event)
      @target.right_pressed = false
      @model.select_event(@target.sx, @target.sy)
      @event_list_panel.select_row(@model.selected_event_no)
      
      self.refresh_menu
      @menu.popup(nil, nil, event.button, event.time)
      
      self.refresh_screen
    end

    def on_right_up(event)
      @menu.popdown
    end
    
    def on_motion_right(event)
    end
    
    def on_motion_left(event)
      @model.move_event(@model.selected_event, @target.sx, @target.sy) if @model.selected_event
    end
    
    def on_motion(event)
		updateTargetCursorPosition(event)
        if @target.left_pressed
          self.on_motion_left(event) 
        end
        if @target.right_pressed
          self.on_motion_right(event)
        end
        self.refresh_screen
    end
    
    def refresh_screen
	  event = @model.selected_event
	  if @target && event
		hit_x = event["pages"][0]["status"]["hit_x"]
		hit_y = event["pages"][0]["status"]["hit_y"]
		off_x = event["pages"][0]["status"]["off_x"]
		off_y = event["pages"][0]["status"]["off_y"]
        chipset = @model.get_chipset(event["pages"][0]["status"]["chip_id"])
		if chipset
			w = [hit_x, chipset.size_x].max
			h = [hit_y, chipset.size_y].max
		else
			w = hit_x
			h = hit_y
		end
		
		rect1 = Rectangle.new(0, 1 - hit_y, hit_x, hit_y)
		rect2 = Rectangle.new(off_x, 1 - chipset.size_y - off_y, chipset.size_x, chipset.size_y)
		tsx = [rect1.left, rect2.left].min
		tsy = [rect1.top, rect2.top].min
		tex = [rect1.right, rect2.right].max
		tey = [rect1.bottom, rect2.bottom].max
	   @target.invalidate(true,
		 tsx,
		 tsy,
		 tex - tsx,
		 tey - tsy
		)
		
		
	   end
    end
    
    def render(s)
      return if @target.x_count == 0
      rect = Rectangle.new(@target.left_count, @target.top_count, @target.x_count, @target.y_count)
      @event_manager.render(s, @target.grid_width, @target.grid_height, rect)
      @target.render_grid(s, @target.grid_width, @target.grid_height)
    end
  end
end